package com.hh.servlet.wxpay;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.JDOMException;

import com.alibaba.fastjson.JSONObject;
import com.hh.servlet.wxpay.util.WeixinService;

/**
 * Servlet implementation class Pay
 */
@WebServlet("/Pay")
public class Pay extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public Pay() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setHeader("content-type", "text/html;charset=UTF-8");
		JSONObject returnObj = new JSONObject();
		
		int type = Integer.parseInt(request.getParameter("type"));
		int payAmount = 0;
		switch(type){
		case 1:
			payAmount = 36500;
			break;
		case 2:
			payAmount = 27000;
			break;
		case 3:
			payAmount = 18000;
			break;
		default:
			payAmount = 0;
			break;
		}
		if(payAmount==0){
			returnObj.put("status", "error");
        	returnObj.put("msg", "请选择缴费类型");
            response.getWriter().print(returnObj.toString());
		}else{
	        String timestamp = String.valueOf(new Date().getTime() / 1000);
	        String trade_no = "TS"+System.currentTimeMillis(); //订单号
	
	        SortedMap<Object, Object> params = new TreeMap<Object, Object>();
	        
	        String openid = (String) request.getSession().getAttribute("openid");
	        if (openid == null) {
	        	returnObj.put("status", "error");
	        	returnObj.put("msg", "当前窗口不支持支付");
	            response.getWriter().print(returnObj.toString());
	        }else{
		        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		        params.put("openid", openid);
		        params.put("trade_type", WeixinService.trade_type);
		        params.put("appid", WeixinService.appid);
		        params.put("body", "消费支付");//商品描述
		        params.put("mch_id", WeixinService.mch_id);//微信支付分配的商户号
		        params.put("nonce_str", WeixinService.getRandomString(32));// 通过微信工具类生成  随机字符串
		        params.put("notify_url", WeixinService.notifyUrl);// 订单结果通知, 微信主动回调此接口
		        params.put("out_trade_no", trade_no); // 订单唯一编号, 不允许重复
		        params.put("spbill_create_ip", request.getRemoteAddr());// 下单ip
		        params.put("total_fee", payAmount+"");// 订单金额, 单位分
		        String sign = WeixinService.createSign(WeixinService.paycharset, params);
		        params.put("sign", sign);
		        String requestXML = WeixinService.getRequestXml(params);
		        String midresult = WeixinService.myhttpsRequest(url,"POST", requestXML).toString();
		        Map<String, String> r_map = null;
				try {
					r_map = WeixinService.doXMLParse(midresult);
				} catch (JDOMException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        //{nonce_str=uyZkgdeMNecYbyuA, appid=wxa0d205221f57bfc1, sign=0D16E06D1DF8323863C28720179E4DCB, trade_type=APP, return_msg=OK, result_code=SUCCESS, mch_id=1575509571, return_code=SUCCESS, prepay_id=wx19104749469120e6c69870b729d2660000}
		
		        if (r_map!=null&&"SUCCESS".equals(r_map.get("return_code").toString())) {
		            String nonce_str = WeixinService.getRandomString(30);
		            String paySign = "";
	                SortedMap<Object, Object> params1 = new TreeMap<Object, Object>();
	                params1.put("appId", WeixinService.appid);
	                params1.put("nonceStr", nonce_str);
	                params1.put("package",
	                        "prepay_id=" + r_map.get("prepay_id"));
	                params1.put("signType", "MD5");
	                params1.put("timeStamp", timestamp);
	                paySign = WeixinService.createSign(WeixinService.paycharset, params1);
	                
	                Map<String, Object> map = new HashMap<String, Object>();
			        map.put("appId", WeixinService.appid);
			        map.put("partnerId", WeixinService.mch_id);
			        map.put("timestamp", timestamp);
			        map.put("nonceStr", nonce_str);
			        map.put("packageValue","prepay_id=" + r_map.get("prepay_id"));
			        map.put("signType", "MD5");
			        map.put("paySign", paySign);
			        map.put("trade_no", trade_no);
		            //更新支付时间 和微信回调时间不同
		            System.out.println(trade_no+"-----------订单支付成功-------------------------------------------------");
		            returnObj.put("status", "success");
		            returnObj.put("data", map);
		            response.getWriter().print(returnObj.toString());
		        } else {
		        	returnObj.put("status", "error");
		        	returnObj.put("msg", "调用失败");
		            response.getWriter().print(returnObj.toString());
		        }
	        }
		}
	}

}
